<?php

namespace addons\shopro\listener;

use addons\shopro\service\Wallet;
use app\admin\model\shopro\commission\Agent as AgentModel;
use app\admin\model\shopro\commission\Level;
use app\admin\model\shopro\commission\Log as LogModel;
use app\admin\model\shopro\commission\Order as CommissionOrderModel;
use addons\shopro\service\commission\Order as OrderService;
use addons\shopro\service\commission\Reward as RewardService;
use addons\shopro\service\commission\Agent as AgentService;
use app\admin\model\shopro\Share as ShareModel;
use app\common\model\Userchildren;

class Commission
{

    /**
     * 用户注册成功
     */
    public function userRegisterAfter($payload)
    {
        $shareInfo = request()->param('shareInfo/a');
        if ($shareInfo) {
            // 注册后添加分享信息
            ShareModel::log($payload['user'], $shareInfo);
        }
        $agent = new AgentService($payload['user']);

        $agent->createNewAgent('user');
    }

    /**
     * 用户分享行为后
     */
    public function userShareAfter($payload)
    {
        $shareInfo = $payload['shareInfo'];

        if ($shareInfo) {

            $user_id = intval($shareInfo->user_id); // 受邀用户

            $share_id = intval($shareInfo->share_id); // 邀请人

            $agent = new AgentService($user_id);
            $bindCheck = $agent->bindUserRelation('share', $share_id);

            // 统计单链业绩
            if ($bindCheck) {
                $agent->createAsyncAgentUpgrade($user_id);
            }
        }
    }

    /**
     * 订单支付后
     */
    public function orderPaidAfter($params)
    {
        // 订单支付成功
        $order = $params['order'];

        // 积分商品订单不参与分销
        if ($order['type'] === 'score') return;

        $user = $params['user'];

        $agent = new AgentService($user);

        // 绑定用户关系
        $agent->bindUserRelation('pay');

        // 先记录分佣 再处理记录业绩、升级等情况
        $items = $order ? $order['items'] : [];

        foreach ($items as $item) {
            if (isset($item['ext']['is_commission']) && !$item['ext']['is_commission']) continue;

            $commission = new OrderService($item);
            // 检查能否分销
            if (!$commission->checkAndSetCommission()) continue;
            // 添加分销订单
            $commissionOrder = $commission->createCommissionOrder();
            if (!$commissionOrder) continue;
            $release = $commissionOrder['amount'];
            $user = \app\common\model\User::where(['id'=>$commissionOrder['buyer_id']])->find();
            jicha($user, $release, $user['level'], $commissionOrder);
            // 执行佣金计划
            $commission->runCommissionPlan($commissionOrder);


            // 支付后拨款
            (new RewardService('paid'))->runCommissionRewardByOrder($commissionOrder);
        }

        // 创建分销商
        $agent->createNewAgent();
        // 分销商数据统计&升级(异步执行) 
        $agent->createAsyncAgentUpgrade();
    }

    /**
     * 充值订单支付成功后
     ** @param $params
     * @return void
     */
    public function orderPaidCommissionAfter($params){
        $orderInfo = $params['order'];
        $userInfo = $params['user'];
        if($userInfo['is_ywy_commion'] == 0 && $userInfo['ywy_user_id'] > 0){
            //查询是否有业务员
            $ywyZhitui = sheep_config('shop.commission.ywy_zhitui')/100;
            $ywyCommission =  $orderInfo['pay_fee']*$ywyZhitui;
            Wallet::change($userInfo['ywy_user_id'], 'commission', $ywyCommission, 'ywy_commission',['order_id'=>$orderInfo['id']],'业务员直推佣金');
            \app\common\model\User::where(['id'=>$userInfo['ywy_user_id']])->update(['is_ywy_commion'=>1]);
        }
        if($userInfo['parent_user_id'] > 0 &&  $userInfo['parent_user_id'] != $userInfo['ywy_user_id']){
            //直推奖励
            $parentUserInfo = \app\common\model\User::where(['id'=>$userInfo['parent_user_id'],'user_type'=>\app\common\model\User::USER_TYPE['vip_user']])->find();

            if($parentUserInfo){
                //直推
                $agentInfo = AgentModel::with(['level_info'])->find($userInfo['parent_user_id']);
                if(isset($agentInfo->level_info->commission_rules['commission_2']) && $agentInfo->level_info->commission_rules['commission_2'] > 0){
                    $parentZhitui = $agentInfo->level_info->commission_rules['commission_2']/100;
                    $zhituiCommission = $parentZhitui * $orderInfo['pay_fee'];
                    Wallet::change($userInfo['parent_user_id'], 'commission', $zhituiCommission, 'parent_commission',['order_id'=>$orderInfo['id']],'直推佣金');
                    $agentInfo->where(['user_id'=>$userInfo['parent_user_id']])->inc('child_order_money_1',$zhituiCommission)->inc('child_order_money_all',$zhituiCommission)->inc('child_order_count_1')->inc('child_order_count_all')->update();
                }
                if($parentUserInfo['ywy_user_id']){
                    //业务员间推
                    $ywyJiantui = sheep_config('shop.commission.ywy_jiantui')/100;
                    $twotuiCommission =  $orderInfo['pay_fee']*$ywyJiantui;
                    if($twotuiCommission > 0){
                        $event  = 'ywy_jiantui_commission';
                        $memo   = '业务员间推佣金';
                        Wallet::change($parentUserInfo['ywy_user_id'], 'commission', $twotuiCommission, $event,['order_id'=>$orderInfo['id']],$memo);
                        AgentModel::where(['user_id'=>$parentUserInfo['ywy_user_id']])->inc('child_order_money_2',$twotuiCommission)->inc('child_order_money_all',$twotuiCommission)->inc('child_order_count_2')->inc('child_order_count_all')->update();
                    }
                }
                //间推
                if($userInfo['two_id']){
                    $twoUserInfo = \app\common\model\User::where(['id'=>$userInfo['two_id']])->find();
                    if($twoUserInfo && $twoUserInfo['user_type'] == \app\common\model\User::USER_TYPE['ywy'] || $twoUserInfo['user_type'] == \app\common\model\User::USER_TYPE['vip_user']){
                        $twotuiCommission = 0;
                        $twoAgentInfo = AgentModel::with(['level_info'])->find($twoUserInfo['id']);
                        if($twoUserInfo['user_type'] == \app\common\model\User::USER_TYPE['ywy']){
                            $ywyJiantui = sheep_config('shop.commission.ywy_jiantui')/100;
                            $twotuiCommission =  $orderInfo['pay_fee']*$ywyJiantui;
                            $event  = 'ywy_jiantui_commission';
                            $memo   = '业务员间推佣金';
                        }else{
                            if(isset($twoAgentInfo->level_info->commission_rules['commission_3']) && $twoAgentInfo->level_info->commission_rules['commission_3'] > 0){
                                $twoZhitui = $twoAgentInfo->level_info->commission_rules['commission_3']/100;
                                $twotuiCommission = $twoZhitui * $orderInfo['pay_fee'];
                                $event  = 'jiantui_commission';
                                $memo   = '间推佣金';
                            }
                        }
                        if($twotuiCommission > 0){
                            Wallet::change($twoUserInfo['id'], 'commission', $twotuiCommission, $event,['order_id'=>$orderInfo['id']],$memo);
                            AgentModel::where(['user_id'=>$twoUserInfo['id']])->inc('child_order_money_2',$twotuiCommission)->inc('child_order_money_all',$twotuiCommission)->inc('child_order_count_2')->inc('child_order_count_all')->update();
                        }

                    }
                }
            }
        }
        chongzhiJicha($userInfo, $orderInfo['pay_fee'], $userInfo['level'], $userInfo['parent_user_id']);
        $this->shengji($userInfo['id']);
    }


    /**
     * 代理升级
     * @param $childrenId
     *
     */
    public function shengji($childrenId){
        $count = Level::where('level','>',1)->count();
        $userIdArr = Userchildren::where(['children_id'=>$childrenId])->where('level','<=',$count)->order('level asc')->column('member_id');
        if($userIdArr) {
            foreach ($userIdArr as $userId) {
                $parentInfo = \app\common\model\User::where(['id' => $userId])->where('user_type', '>', 0)->find();
                if ($parentInfo) {

                    $xiaCount = \app\common\model\User::where(['parent_user_id' => $userId,'level'=>$parentInfo['level']])->where('user_type', '=',
                        3)->count();
                    $userAgent = AgentModel::with(['level_info'])->find($userId);
                    if(empty($userAgent->level_info->upgrade_rules['child_user_count_1'])){
                        $child_user_count_1 = 3;
                    }else{
                        $child_user_count_1 = $userAgent->level_info->upgrade_rules['child_user_count_1'];
                    }
                    if($xiaCount >= $child_user_count_1){
                        //升级
//                        echo '------------------';
                        $levelInfo = Level::where('level', '>', $userAgent->level)->order('level asc')->find();
                        if($levelInfo){
                            $userAgent->level = $levelInfo->level;
                            $userAgent->save();
                            $parentInfo->level = $levelInfo->level;
                            $parentInfo->save();
                            LogModel::add($userId, 'agent', ['type' => 'level', 'level' =>  $levelInfo]);
                        }
                    }
                }
            }
        }
    }

    // 线下付款后
    public function orderOfflinePaidAfter($params)
    {
        $this->orderPaidAfter($params);
    }

    /**
     * 订单确认收货
     */
    public function orderConfirmFinish($params)
    {
        $order = $params['order'];

        $service = new RewardService('confirm');
        $commissionOrders = collection(CommissionOrderModel::where('order_id', $order->id)->select());
        $commissionOrders->each(function ($commissionOrder) use ($service) {
            $service->runCommissionRewardByOrder($commissionOrder);
        });
    }

    /**
     * 订单完成
     */
    public function orderFinish($params)
    {
        $order = $params['order'];

        $service = new RewardService('finish');
        $commissionOrders = collection(CommissionOrderModel::where('order_id', $order->id)->select());
        $commissionOrders->each(function ($commissionOrder) use ($service) {
            $service->runCommissionRewardByOrder($commissionOrder);
        });
    }

    /**
     * 订单退款后
     */
    public function orderItemRefundAfter($params)
    {
        $order = $params['order'];
        $item = $params['item'];

        $commissionOrder = CommissionOrderModel::where('order_id', $order->id)->where('order_item_id', $item->id)->find();

        if (!$commissionOrder) return;

        (new RewardService('refund'))->backCommissionRewardByOrder($commissionOrder);
    }
}
